<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta content="width=device-width, initial-scale=1.0" name="viewport">
    <title>WebSocket Client</title>
</head>
<body>
<h1>WebSocket Client</h1>
<button onclick="connectWebSocket()">connect</button>
<br>
<input id="messageInput" placeholder="Type a message" type="text">
<button onclick="sendMessage()">Send</button>
<div id="messages"></div>

<script>
    let socket;

    function connectWebSocket() {
        socket = new WebSocket('ws://localhost:8000/ws'); // 确保URL与后端配置一致

        socket.onopen = function (event) {
            console.log('Connected to WebSocket server');
            appendMessage('Connected to WebSocket server');
        };

        socket.onmessage = function (event) {
            console.log('Message from server:', event.data);
            appendMessage('Server: ' + event.data);
        };

        socket.onclose = function (event) {
            console.log('Disconnected from WebSocket server');
            appendMessage('Disconnected from WebSocket server');
        };

        socket.onerror = function (error) {
            console.error('WebSocket error:', error);
            appendMessage('WebSocket error: ' + error.message);
        };
    }

    function sendMessage() {
        const input = document.getElementById('messageInput');
        const message = input.value;
        if (socket && socket.readyState === WebSocket.OPEN) {
            socket.send(message);
            appendMessage('You: ' + message);
            input.value = ''; // 清空输入框
        } else {
            alert('WebSocket is not connected.');
        }
    }

    function appendMessage(message) {
        const messagesDiv = document.getElementById('messages');
        const messageElement = document.createElement('div');
        messageElement.textContent = message;
        messagesDiv.appendChild(messageElement);
    }

</script>
</body>
</html>